import { LoadingOutlined, ReloadOutlined } from '@ant-design/icons'
import client, {
  DatasourceInstanceVo,
  ModelGetUserPermission,
} from '@lib/client'
import { Card, CardTable, Toolbar } from '@lib/components'
import { formatDate } from '@lib/utils/date'
import { useClientRequest } from '@lib/utils/useClientRequest'
import { message, Popconfirm, Select, Space, Tooltip } from 'antd'
import { IColumn } from 'office-ui-fabric-react/lib/DetailsList'
import { ScrollablePane } from 'office-ui-fabric-react/lib/ScrollablePane'
import React, { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import CreatePermissionButton from './CreatePermissionButton'

const { Option } = Select

interface IExpandedItem extends ModelGetUserPermission {
  key: string
  index: number
}

function expandItems(rows: ModelGetUserPermission[]): IExpandedItem[] {
  const expanded: IExpandedItem[] = []
  let index = 1
  rows.forEach((row) => {
    expanded.push({
      key: row.id ? row.id + '' : '',
      index: index++,
      ...row,
    })
  })
  return expanded
}

export default function PermissionList() {
  const { t } = useTranslation()
  const [curInstance, setCurInstance] = useState('')
  const [instanceData, setInstanceData] = useState([] as DatasourceInstanceVo[])
  const [permissionData, setPermissionData] = useState([] as IExpandedItem[])

  const {
    data: listInstancesResponse,
    isLoading,
    sendRequest: listInstance,
  } = useClientRequest(
    (reqConfig) => client.getInstance().listInstances(reqConfig),
    { immediate: true }
  )

  const {
    data: getPermissionResponse,
    isLoading: tableLoading,
    error,
    sendRequest: getPermission,
  } = useClientRequest(
    (reqConfig) => client.getInstance().getPermission(curInstance),
    { immediate: false }
  )

  useEffect(() => {
    const instanceData = listInstancesResponse?.instances ?? []
    setInstanceData(instanceData)
    if (instanceData.length > 0) {
      setCurInstance(instanceData[0].id + '')
    }
  }, [listInstancesResponse])

  useEffect(() => {
    if (curInstance) {
      getPermission()
    }
  }, [curInstance])

  useEffect(() => {
    setPermissionData(expandItems(getPermissionResponse?.permissions ?? []))
  }, [getPermissionResponse])

  const handleDeletePermission = async (instanceId) => {
    const r = await client.getInstance().deletePermission(instanceId)
    if (r.status == 200) {
      message.success('Success')
      await listInstance()
    }
  }

  const handleInstanceChange = (value) => {
    setCurInstance(value)
  }

  const columns: IColumn[] = useMemo(
    () => [
      {
        name: t('instance_permission.list.permission_table.columns.index'),
        key: 'index',
        minWidth: 100,
        maxWidth: 150,
        onRender: (row: IExpandedItem) => {
          return row.index
        },
      },
      {
        name: t(
          'instance_permission.list.permission_table.columns.description'
        ),
        key: 'description',
        minWidth: 300,
        maxWidth: 400,
        onRender: (row: IExpandedItem) => {
          if (row.description == null || row.description.length <= 0) {
            return row.name
          }
          return row.description
        },
      },
      {
        name: t(
          'instance_permission.list.permission_table.columns.create_time'
        ),
        key: 'create_time',
        minWidth: 300,
        maxWidth: 400,
        onRender: (row: IExpandedItem) => {
          if (row.create_time) {
            return formatDate(new Date(row.create_time))
          }
          return row.create_time
        },
      },
      {
        name: t('instance_permission.list.permission_table.columns.action'),
        key: 'action',
        minWidth: 200,
        maxWidth: 300,
        onRender: (row: IExpandedItem) => {
          return (
            <Space>
              <Popconfirm
                placement="bottom"
                title={t('instance_permission.button.delete_permission.tip')}
                onConfirm={() => handleDeletePermission(row.id)}
                okText={t(
                  'instance_permission.button.delete_permission.submit'
                )}
                cancelText={t(
                  'instance_permission.button.delete_permission.cancel'
                )}
              >
                <a href="">
                  {t('instance_permission.button.delete_permission.title')}
                </a>
              </Popconfirm>
            </Space>
          )
        },
      },
    ],
    [t]
  )

  return (
    <div
      style={{
        height: 'calc(100vh - 48px)',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      <Card>
        <Toolbar>
          <Space>
            <Select
              value={curInstance}
              onChange={handleInstanceChange}
              loading={isLoading}
              style={{ width: 200 }}
            >
              {instanceData &&
                instanceData.map((item) => (
                  <Option key={item.id} value={item.id + ''}>
                    {item.name}
                  </Option>
                ))}
            </Select>
            <CreatePermissionButton
              refresh={getPermission}
              instaceId={Number(curInstance)}
            />
          </Space>
          <Space>
            <Tooltip title={t('statement.pages.overview.toolbar.refresh')}>
              {isLoading ? (
                <LoadingOutlined />
              ) : (
                <ReloadOutlined onClick={getPermission} />
              )}
            </Tooltip>
          </Space>
        </Toolbar>
      </Card>

      <div style={{ height: '100%', position: 'relative' }}>
        <ScrollablePane>
          <CardTable
            cardNoMarginTop
            loading={tableLoading}
            columns={columns}
            items={permissionData}
            errors={error}
          />
        </ScrollablePane>
      </div>
    </div>
  )
}
